package com.ruoyi.udp_server;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.uav.domain.UavTaskRecord;
import com.ruoyi.uav.domain.UavTaskSteps;
import com.ruoyi.uav.domain.vo.CoordinateInfoData;
import com.ruoyi.uav.domain.vo.TaskInfoData;
import com.ruoyi.uav.service.IUavTaskRecordService;
import com.ruoyi.uav.service.IUavTaskStepsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class QGCMessageHanding {

    @Resource
    private IUavTaskRecordService uavTaskRecordService;

    @Resource
    private IUavTaskStepsService uavTaskStepsService;
    public void MessageHanding(String data) {

        ObjectMapper objectMapper = new ObjectMapper();
        TaskInfoData taskInfoData;
        try {
            taskInfoData = objectMapper.readValue(data, TaskInfoData.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        System.out.println("taskRecordId:" + taskInfoData.getTaskRecordId() + " taskSteps:" + taskInfoData.getTaskSteps());
        updateTaskRecord(taskInfoData.getTaskRecordId(), taskInfoData.getTaskSteps());
        saveTaskSteps(taskInfoData.getTaskRecordId(), taskInfoData.getTaskSteps());

    }

    private void saveTaskSteps(Long taskRecordId, String taskSteps) {
        UavTaskSteps uavTaskSteps = new UavTaskSteps();
        uavTaskSteps.setStepsInfo(taskSteps);
        uavTaskSteps.setTaskRecordId(taskRecordId);
        uavTaskStepsService.save(uavTaskSteps);
    }

    private void updateTaskRecord(Long taskRecordId, String taskSteps) {
        UavTaskRecord uavTaskRecord = uavTaskRecordService.getById(taskRecordId);

        if (uavTaskRecord.getTrainingId() == 12) {
            List<CoordinateInfoData> waypoints = new ArrayList<>();
            waypoints.add(new CoordinateInfoData(116.25930, 40.15418, 15.00));
            waypoints.add(new CoordinateInfoData(116.25955, 40.15435, 25.00));
            uavTaskRecord.setScore(verifyWaypoints(taskSteps, waypoints));
        }else {
            uavTaskRecord.setScore(100L);
        }

        uavTaskRecord.setStatus("2");

        Date createTime = uavTaskRecord.getCreateTime();
        Duration duration = Duration.between(createTime.toInstant(), Instant.now()); // 计算两个时间点的差值
        String completeTime = formatDuration(duration); // 转换为分秒格式的字符串
        uavTaskRecord.setCompleteTime(completeTime);
        uavTaskRecordService.updateById(uavTaskRecord);
    }

    /**
     * 将Duration对象转换为分秒格式的字符串
     * @param duration Duration对象
     * @return 分秒格式的字符串
     */
    private String formatDuration(Duration duration) {
        long minutes = duration.toMinutes();
        long seconds = duration.getSeconds() % 60;

        return String.format("%d分钟%d秒", minutes, seconds);
    }

    private Long verifyWaypoints(String taskSteps, List<CoordinateInfoData> waypoints) {
        JSONObject stepsObject = JSONObject.parseObject(taskSteps);
        int size = waypoints.size();
        int currentIndex = 1;
        int completedNumber = 0;
        StringBuilder errorLog = new StringBuilder();

        for (int i = 0; i < size; i++) {

            JSONObject waypoint = stepsObject.getJSONObject("航点" + currentIndex++);
            // 从航点1的JSONObject中获取高度
            double height = waypoint.getDouble("高度");
            double longitude = waypoint.getDouble("经度");
            double latitude = waypoint.getDouble("纬度");

            if (Math.abs(height - waypoints.get(i).getAltitude()) <= 1
                    && Math.abs(longitude - waypoints.get(i).getLongitude()) <= 0.00001
                    && Math.abs(latitude - waypoints.get(i).getLatitude()) <= 0.00001) {
                completedNumber++;
            }else {
                errorLog.append("航点").append(currentIndex).append("错误\n");
            }

        }

        return (long) (completedNumber / (double) size * 100);
    }

}
